package tmproject.hlhj.fhp.tmvote.network

import android.content.Context
import com.google.gson.Gson
import com.lzy.okgo.model.Response
import rx.Observable
import rx.Observer
import rx.Subscriber
import tmproject.hlhj.fhp.tmvote.beans.BaseBean
import tmproject.hlhj.fhp.tmvote.log
import tmproject.hlhj.fhp.tmvote.toast
import tmproject.hlhj.fhp.tmvote.utils.ToastUtil

/**
 * Created by Never Fear   on 2018\8\6 0006.
Never More....
 */
interface BaseAction<T> :Observer<T> {
    override fun onNext(t: T) {
        if (t is Response<*>){
            if (!t.isFromCache){
                log("okgo","从网络中来")
                val response = t as Response<*>
                val body = response.body()
                val bodyStr = Gson().toJson(body)
                val baseBean = Gson().fromJson(bodyStr, BaseBean::class.java)
                if (baseBean.code==200){
                    onRespSuccess(t)
                }else{
                    onRespErro(t)
                }
            }else{
                log("okgo","从缓存中来")
                if (!t.isSuccessful){
                    onHttpFailed()
                }else{
                    val response = t as Response<*>
                    val body = response.body()
                    val bodyStr = Gson().toJson(body)
                    val baseBean = Gson().fromJson(bodyStr, BaseBean::class.java)
                    if (baseBean.code==200){
                        log("okgo","请求成功")
                        onacheSuccess(t)
                    }else{
                        log("okgo","请求失败")
                        onRespErro(t)
                    }
                }
            }

        }else{
            ToastUtil.toast("这就不是一个Response型数据")
        }
    }

    override fun onCompleted() {
//        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
    override fun onError(e: Throwable?) {
        log("okgo","网络请求时错误-------------"+e.toString())
        e?.printStackTrace()
    }
    fun onHttpFailed()
    abstract fun onRespSuccess(t:T)
    abstract fun onacheSuccess(t:T)
    abstract fun onRespErro(t:T)
}